package com.firewolf.springsecurity.base.controller;

import com.firewolf.springsecurity.base.entities.User;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Arrays;
import java.util.List;

/**
 * 作者：刘兴
 * 时间:18/11/25
 **/
@RestController
@RequestMapping("user")
public class UserController {

    /**
     * 新增
     * @param user
     * @return
     */
    @PostMapping
    public String add(User user) {
        System.out.println(ReflectionToStringBuilder.toString(user));
        return "add ok";
    }


    /**
     * 查询列表
     * @return
     */
    @GetMapping
    public List<User> list() {
        return Arrays.asList(
                new User(1, "lx", 34, "篮球"),
                new User(2, "ls", 30, "羽毛球")
        );
    }


    /**
     * 修改
     * @param user
     * @return
     */
    @PutMapping
    public String update(User user){
        System.out.println(ReflectionToStringBuilder.toString(user));
        return "update ok";
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        System.out.println("要删除的用户ID为："+id);
        return "delete ok";
    }

    //***************下面这些是SpringSecurity集成的方法******************
    /**
     *
     HttpServletRequest#getRemoteUser() //获取远程用户
     HttpServletRequest.html#getUserPrincipal() //获取用户信息
     HttpServletRequest.html#isUserInRole(java.lang.String) //判断用户是否有角色
     HttpServletRequest.html#login(java.lang.String, java.lang.String) //用户登录
     HttpServletRequest.html#logout() //用户注销
     *
     */

    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping("logout")
    public String logout(HttpServletRequest request) {
        try {
            request.logout();
        } catch (ServletException e) {
            e.printStackTrace();
        }
        return "logout";
    }

    /**
     * 查看用户信息
     * @param request
     * @return
     */
    @GetMapping("info")
    public String info(HttpServletRequest request) {
        Principal principal = request.getUserPrincipal();
        String name = principal.getName();
        System.out.println(name);
        return name;
    }
}
